package main.social.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import main.social.entities.Entrys;
import main.social.entities.Users;
import main.social.service.EntryService;
import main.social.service.UserService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/PhotoView")
public class PhotoViewController {

	private EntryService entryService;
	private UserService userService;
	
	public void setEntryService(EntryService entryService) {
		this.entryService = entryService;
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView show(){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("PhotoView");
		return mav;
	}

	@RequestMapping(value = "/{ItemId}", method = RequestMethod.GET)
	public ModelAndView show(@PathVariable("ItemId") String itemId, HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("PhotoView");
		Entrys item = this.entryService.increaseView(itemId);
		List<Entrys> childs = this.entryService.getCommentEntrysByUuid(itemId);
		boolean isOwner = false;
		Users user = null;
		if(request.getSession().getAttribute("LOGEDIN_USER") != null){
			String username = request.getSession().getAttribute("LOGEDIN_USER").toString();
			if(username == item.getUser().getAccount().getUsername()){
				isOwner = true;
			}
			user = this.userService.getByUsername(username);
		}
		mav.addObject("item", item);
		mav.addObject("childs", childs);
		mav.addObject("user", user);
		mav.addObject("isOwner", isOwner);
		return mav;
	}
	
	@RequestMapping(value = "/{ItemId}", method = RequestMethod.POST)
	public String addComment(@PathVariable("ItemId") String itemId, @RequestParam("content") String content,
										HttpServletRequest request){
		if(request.getSession().getAttribute("LOGEDIN_USER")==null){
			return "Login";
		}
		String username = request.getSession().getAttribute("LOGEDIN_USER").toString();
		if(this.entryService.postComment(username, itemId, content)){
			return "redirect:" + itemId;
		}else{
			return "Error";
		}
	}
}
